<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\planpart;

use app\common\lib\Common;
use app\common\lib\RedisQueue;
use app\model\novel\NovelChapterModel;
use app\model\redis\RedisQueueModel;
use app\model\plan\NovelChapterPartOverseaModel;
use app\model\plan\PromotionPlanOverseaModel;
use support\Cache;
use Webman\RedisQueue\Consumer;

class AsyncPlanPartOversea  implements Consumer
{
    // 要消费的队列名
    public $queue = 'asyncPlanPartOversea';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try{
            // 无需反序列化
            //var_export($data);
            //var_export('redis_queue_asyncUploadVideo');
            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (\Throwable $e){
            $cacheKey = 'async_plan_part_oversea_'.$data['requestid'];
            Cache::set($cacheKey,['progress'=>-1,'error'=>$e->getMessage()],7200);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }
    }

    protected function handle($data)
    {
        $cacheKey = 'async_plan_part_oversea_'.$data['requestid'];
        Cache::set($cacheKey,['progress'=>'0'],7200);

        //todo 1 生成创作内容片段
        $batch = $this->generatedPart($data);
        Cache::set($cacheKey,['progress'=>'30'],7200);

        //todo 2 生成创作内容片段-字幕
        $this->generatedSubtitle($data,$batch);
        Cache::set($cacheKey,['progress'=>'60'],7200);

        //todo 3 生成创作内容片段-配音
        $this->generatedTencentTimbre($data,$batch);
        Cache::set($cacheKey,['progress'=>'100'],7200);

        return ['success'];
    }

    protected function generatedPart($data)
    {
        $novelSn = PromotionPlanOverseaModel::getInstance()->getWhere(['id'=>$data['planid']])->value('novel_sn');
        $chapterid = PromotionPlanOverseaModel::getInstance()->getWhere(['id'=>$data['planid']])->value('chapterid');
        $content = NovelChapterModel::getInstance()->getWhere(['id'=>$chapterid])->value('content');

        $contents = array_values(array_filter(explode("\n",$content)));
        foreach($contents as $k=>$content) {
            $content = preg_replace('/^\d+[\.]+/', '', $content);
            if (empty($content)) {
               unset($contents[$k]);
            }
        }
        $contents = array_values($contents);

        //插入内容片段
        $batch = date('ymdHis').mt_rand(10,99);

        $insert = [];
        foreach($contents as $k=>$content){
            if(empty($content)){
                continue;
            }
            $content = preg_replace('/^\d+[\.]+/','',$content);
            $insert[] = [
                'planid'=>$data['planid'],
                'novel_sn'=>$novelSn,
                'chapterid'=>$chapterid,
                'content'=>$content,
                'number'=>$k+1,
                'batch'=>$batch,
            ];
        }

        $insert && NovelChapterPartOverseaModel::getInstance()->getWhere(['planid'=>$data['planid']])->update(['isdel'=>time()]);
        $insert && NovelChapterPartOverseaModel::getInstance()->insert($insert);
        $insert && PromotionPlanOverseaModel::getInstance()->getWhere(['id'=>$data['planid']])->update(['part_nums'=>count($insert),'status'=>1]);

        return $batch;
    }

    protected function generatedSubtitle($data,$batch)
    {
        $parts = NovelChapterPartOverseaModel::getInstance()->getWhere(['planid'=>$data['planid'],'batch'=>$batch,'isdel'=>0])
                                                     ->orderBy('number','asc')->get();
        foreach ($parts as $val){
            $replaceStr =  ['`','~','!','@','#','$','^','&','*','(',')','=','|','{','}','\\',':',';',',','[',']','.','+','-','_',
                            '<','>','《','》','/','?','！','￥','……','（','）','――','|','【','】',
                            '‘','；','：','”','“','。','，','、','？',', ','\'','"','’',' '];
            $content = str_replace($replaceStr, "\n",$val['content']);
            $contents = array_values(array_filter(explode("\n",$content)));

            $val->subtitle = json_encode($contents,256);
            $val->save();
        }

        return true;
    }

    protected function generatedTencentTimbre($data,$batch)
    {
        //队列名
        $queue = 'generateTimbre';

        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>Common::getRequestId(), 'planid'=>$data['planid'], 'batch'=>$batch, 'source'=>'plan_part_oversea'];

        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return true;
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}